<?php
namespace app\admin\controller;
use think\Request;
use think\Session;
use think\Config;
use think\Controller;
use app\common\model\User;
class LoginController extends Controller{
  public function __construct(\think\Request $request = null) {
    parent::__construct($request);

    // 读取网站设置
    settings();

    $site_root = Config::get("site_root");
    $this->assign("site_root", $site_root);
    
    // 当前页面记录
    $this->request = Request::instance();
  }

  function index(){
    $this->redirect("login");
  }

  function login(){
    $request = Request::instance();
    $manager = login_manager();
    if($manager){
      if($request->isGet()){
        $this->redirect("index/index");
      }else{
        $this->success("登录成功", "index/index", '', 0);
      }
    }
    
    if($request->isPost()){
      $param = $request->param();
      $Model = new User();
      $user = $Model->managerLogin($param["name"], $param["password"]);
      // return json($user);
      if(empty($user)){
        $this->error("登录失败");
      }else{
        if(isset($param["is_remember"])){
          $expire = 7*24*3600;
        }else{
          $expire = 24*3600;
        }
        Session::init(["expire" => $expire]);
        Session::set("manager", $user);

        $back_url = Session::pull('back_url');
        if(empty($back_url)){
          $back_url = url("index/index");
        }
        $this->success("登录成功", $back_url);
      }
    }else{
      return $this->fetch("login");
    }
  }

  function logout(){
    Session::delete("manager");
    $this->redirect("login");
  }
}